package com.chushouya.order.service.api.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.chushouya.common.constant.DangDangConstants;
import com.chushouya.order.constants.DangDangOrderStatusEnum;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.entity.OrderClothesProductEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.repository.OrderAddressRepository;
import com.chushouya.order.dao.repository.OrderClothesProductRepository;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.api.dangdang.DangDangCancelOrderRequest;
import com.chushouya.order.dto.api.dangdang.DangDangCreateOrderRequest;
import com.chushouya.order.dto.api.dangdang.DangDangCreateOrderResponse;
import com.chushouya.order.dto.api.dangdang.DangDangOrderPushDTO;
import com.chushouya.order.dto.api.dangdang.DangDangResponse;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.service.api.DangDangApiService;
import com.chushouya.common.util.DangDangSignUtil;
import com.chushouya.order.service.common.OrderLogService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 铛铛API服务实现
 */
@Slf4j
@Service
public class DangDangApiServiceImpl implements DangDangApiService {


    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderClothesProductRepository orderClothesProductRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;

    @Resource
    private OrderLogService orderLogService;


    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单信息不存在");
        }
        return orderEntity;
    }

    /**
     * 获取产品信息
     */
    private OrderClothesProductEntity getProductInfo(Long orderId) {
        OrderClothesProductEntity productEntity = orderClothesProductRepository.selectByOrderId(orderId);
        if (Objects.isNull(productEntity)) {
            throw Ex.business("订单产品信息不存在");
        }
        return productEntity;
    }

    /**
     * 获取订单额外信息
     */
    private OrderExtendEntity getOrderExtraInfo(Long orderId) {
        OrderExtendEntity orderExtendEntity = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtendEntity)) {
            throw Ex.business("订单额外信息不存在");
        }
        return orderExtendEntity;
    }

    /**
     * 获取用户地址信息
     * @return
     */
    private OrderAddressEntity getUserAddress(Long orderId) {
        OrderAddressEntity orderAddressEntity = orderAddressRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderAddressEntity)) {
            throw Ex.business("订单地址信息不存在");
        }
        return orderAddressEntity;
    }

    @Override
    public DangDangResponse<DangDangCreateOrderResponse> createOrder(DangDangCreateOrderRequest request) {
        return doCreateOrder(request, DangDangConstants.PROD_BASE_URL);
    }

    @Override
    public DangDangResponse<DangDangCreateOrderResponse> createOrderTest(DangDangCreateOrderRequest request) {
        return doCreateOrder(request, DangDangConstants.TEST_BASE_URL);
    }

    @Override
    public DangDangResponse<DangDangCreateOrderResponse> createOrder(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        OrderAddressEntity addressEntity = getUserAddress(orderId);
        OrderClothesProductEntity productInfo =  getProductInfo(orderId);
        OrderExtendEntity orderExtendEntity = getOrderExtraInfo(orderId);
        // 创建测试订单数据
        DangDangCreateOrderRequest request = new DangDangCreateOrderRequest();
        request.setAddress(Strings.format("{} {} {} {}",
                addressEntity.getProvince(),
                addressEntity.getCity(),
                addressEntity.getDistrict(),
                addressEntity.getAddress()));
        request.setChannelId("30083");

        Date appointStartTime = orderEntity.getAppointStartTime();
        Date appointEndTime = orderEntity.getAppointEndTime();

        // 设置时间为明天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");   // 明天上午11点

        String startTime = sdf.format(appointStartTime);
        String endTime = sdf.format(appointEndTime);
        String startTimeOnly = timeFormat.format(appointStartTime);
        String endTimeOnly = timeFormat.format(appointEndTime);

        request.setStarttime(startTime);
        request.setEndtime(endTime);
        request.setGoGomeTime(sdf.format(appointStartTime).substring(0, 10) + " " + startTimeOnly + "-" + endTimeOnly);

        request.setTel(addressEntity.getUserPhone());
        request.setType(DangDangConstants.ORDER_TYPE_CLOTHES);
        request.setUserName(addressEntity.getUserName());
        request.setWeight(productInfo.getWeightRange());
        request.setOrderSn(orderEntity.getOrderNo());
        request.setOpenId(orderExtendEntity.getOpenId());

        log.info("创建铛铛测试订单: {}, 订单ID: {}", request.getOrderSn(), orderId);
        
        // 调用创建订单接口（测试环境）
        DangDangResponse<DangDangCreateOrderResponse> response = createOrder(request);
        
        // 创建完成插入日志
        if (response.isSuccess()) {
            orderLogService.addOrderActionLog(
                    orderId,
                    OrderActionEnum.FOLLOW_ORDER.value(),
                    Strings.format("铛铛创建订单成功，订单号: {}", request.getOrderSn()));
        }else{
            orderLogService.addOrderActionLog(
                    orderId,
                    OrderActionEnum.FOLLOW_ORDER.value(),
                    Strings.format("铛铛创建订单失败 {}", response.getMsg()));
        }
        
        return response;
    }

    /**
     * 执行创建订单请求
     * @param request 请求参数
     * @param baseUrl 基础URL
     * @return 响应结果
     */
    private DangDangResponse<DangDangCreateOrderResponse> doCreateOrder(DangDangCreateOrderRequest request, String baseUrl) {
        try {
            // 生成签名参数
            String timestamp = DangDangSignUtil.getCurrentTimestamp();
            String sign = DangDangSignUtil.generateSign(DangDangConstants.APP_ID, DangDangConstants.APP_SECRET, timestamp);
            
            String url = baseUrl + DangDangConstants.CREATE_ORDER_PATH;
            
            log.info("铛铛创建订单请求开始，URL: {}, 订单号: {}", url, request.getOrderSn());
            log.debug("请求参数: {}", JSONUtil.toJsonStr(request));
            
            // 发送HTTP请求
            String responseBody = HttpRequest.post(url)
                    .header("Content-Type", "application/json; charset=utf-8")
                    .header(DangDangConstants.HEADER_APP_ID, DangDangConstants.APP_ID)
                    .header(DangDangConstants.HEADER_TIMESTAMP, timestamp)
                    .header(DangDangConstants.HEADER_SIGN, sign)
                    .body(JSONUtil.toJsonStr(request))
                    .execute()
                    .body();
            
            log.info("铛铛创建订单响应: {}", responseBody);
            
            // 解析响应
            DangDangResponse<DangDangCreateOrderResponse> response;
            try {
                // 先解析为基础响应对象
                cn.hutool.json.JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                
                response = new DangDangResponse<>();
                response.setCode(jsonResponse.getInt("code"));
                response.setMsg(jsonResponse.getStr("msg"));
                
                // 处理 data 字段
                Object dataObj = jsonResponse.get("data");
                if (dataObj != null && !(dataObj instanceof cn.hutool.json.JSONNull)) {
                    if (response.isSuccess() && dataObj instanceof cn.hutool.json.JSONObject) {
                        // 成功时转换为具体的响应对象
                        DangDangCreateOrderResponse orderResponse = JSONUtil.toBean(
                                JSONUtil.toJsonStr(dataObj), DangDangCreateOrderResponse.class);
                        response.setData(orderResponse);
                    } else {
                        // 其他情况保持原始数据
                        response.setData((DangDangCreateOrderResponse) dataObj);
                    }
                }
            } catch (Exception parseException) {
                log.error("解析铛铛响应失败: {}", responseBody, parseException);
                response = new DangDangResponse<>();
                response.setCode(-1);
                response.setMsg("响应解析失败: " + parseException.getMessage());
            }
            
            if (response.isSuccess()) {
                log.info("铛铛创建订单成功，订单号: {}", request.getOrderSn());
            } else {
                log.error("铛铛创建订单失败，订单号: {}, 错误码: {}, 错误信息: {}", 
                        request.getOrderSn(), response.getCode(), response.getMsg());
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("铛铛创建订单异常，订单号: {}", request.getOrderSn(), e);
            
            DangDangResponse<DangDangCreateOrderResponse> errorResponse = new DangDangResponse<>();
            errorResponse.setCode(-1);
            errorResponse.setMsg("系统异常: " + e.getMessage());
            return errorResponse;
        }
    }

    @Override
    public void handleOrderPush(DangDangOrderPushDTO orderPushDTO) {
        log.info("开始处理当当订单推送: {}", JSONUtil.toJsonStr(orderPushDTO));
        
        try {
            // 根据订单号查找订单
            OrderQuery query = new OrderQuery();
            query.setOrderNo(orderPushDTO.getOrderId());
            OrderEntity order = orderRepository.selectOne(query);
            
            if (Objects.isNull(order)) {
                throw Ex.business("订单不存在，订单号: " + orderPushDTO.getOrderId());
            }
            
            Long orderId = order.getOrderId();
            Integer dangdangStatus = orderPushDTO.getOrderStatus();
            
            // 获取当当订单状态枚举
            DangDangOrderStatusEnum dangdangStatusEnum = DangDangOrderStatusEnum.getByValue(dangdangStatus);
            if (dangdangStatusEnum == null) {
                log.warn("未知的当当订单状态: {}", dangdangStatus);
                return;
            }
            
            // 构建日志信息
            StringBuilder logMessage = new StringBuilder();
            logMessage.append("当当订单推送 - ");
            logMessage.append("状态: ").append(dangdangStatusEnum.getDesc());
            logMessage.append("(").append(dangdangStatus).append(")");
            logMessage.append(" -> 系统状态: ").append(dangdangStatusEnum.getSystemStatus().named());
            logMessage.append("(").append(dangdangStatusEnum.getSystemStatus().value()).append(")");
            
            if (orderPushDTO.getWeight() != null && orderPushDTO.getWeight() > 0) {
                logMessage.append(", 重量: ").append(orderPushDTO.getWeight()).append("kg");
            }
            
            if (Strings.isNotBlank(orderPushDTO.getCloseInfo())) {
                logMessage.append(", 关闭原因: ").append(orderPushDTO.getCloseInfo());
            }
            
            if (Strings.isNotBlank(orderPushDTO.getOpenId())) {
                logMessage.append(", OpenId: ").append(orderPushDTO.getOpenId());
            }
            
            // 写入订单日志
            orderLogService.addOrderActionLog(
                orderId,
                "铛铛系统",
                OrderActionEnum.FOLLOW_ORDER.value(),
                logMessage.toString()
            );
            
            // 判断是否需要更新系统订单状态
            if (dangdangStatusEnum.isNeedPush()) {
                OrderEntity updateOrder = new OrderEntity();
                updateOrder.setOrderId(orderId);
                updateOrder.setOrderStatus(dangdangStatusEnum.getSystemStatus().value());
                orderRepository.updateByPrimaryKeySelective(updateOrder);
                
                log.info("已更新订单状态，订单ID: {}, 当当状态: {} -> 系统状态: {}",
                    orderId, dangdangStatusEnum.getDesc(), dangdangStatusEnum.getSystemStatus().named());
            } else {
                log.info("当当状态 {} 不需要更新系统订单状态", dangdangStatusEnum.getDesc());
            }
            
            log.info("当当订单推送处理完成，订单ID: {}, 订单号: {}, 当当状态: {}", 
                orderId, orderPushDTO.getOrderId(), dangdangStatusEnum.getDesc());
            
        } catch (Exception e) {
            log.error("处理当当订单推送失败: {}", JSONUtil.toJsonStr(orderPushDTO), e);
            throw e;
        }
    }

    @Override
    public DangDangResponse<Void> cancelOrder(String orderSn, String closeInfo) {
        log.info("开始取消当当订单: orderSn={}, closeInfo={}", orderSn, closeInfo);
        
        try {
            // 根据订单号查找订单
            OrderQuery query = new OrderQuery();
            query.setOrderNo(orderSn);
            OrderEntity order = orderRepository.selectOne(query);
            
            if (Objects.isNull(order)) {
                log.warn("订单不存在，订单号: {}", orderSn);
                DangDangResponse<Void> response = new DangDangResponse<>();
                response.setCode(-1);
                response.setMsg("订单不存在");
                return response;
            }
            
            Long orderId = order.getOrderId();
            
            // 检查订单状态是否可以取消
            Integer currentStatus = order.getOrderStatus();
            if (OrderStatusEnum.CANCELLED.value().equals(currentStatus)) {
                log.info("订单已经是取消状态，订单ID: {}, 订单号: {}", orderId, orderSn);
                DangDangResponse<Void> response = new DangDangResponse<>();
                response.setCode(DangDangConstants.SUCCESS_CODE);
                response.setMsg("订单已取消");
                return response;
            }
            
            // 更新订单状态为已取消
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setOrderId(orderId);
            updateOrder.setOrderStatus(OrderStatusEnum.CANCELLED.value());
            orderRepository.updateByPrimaryKeySelective(updateOrder);
            
            // 记录订单日志
            String logMessage = Strings.format("当当取消订单 - 取消原因: {}", closeInfo);
            orderLogService.addOrderActionLog(
                orderId,
                "铛铛系统",
                OrderActionEnum.CANCEL_ORDER.value(),
                logMessage
            );
            
            log.info("当当订单取消成功，订单ID: {}, 订单号: {}, 取消原因: {}", 
                orderId, orderSn, closeInfo);
            
            DangDangResponse<Void> response = new DangDangResponse<>();
            response.setCode(DangDangConstants.SUCCESS_CODE);
            response.setMsg("取消成功");
            return response;
            
        } catch (Exception e) {
            log.error("取消当当订单异常，订单号: {}", orderSn, e);
            
            DangDangResponse<Void> errorResponse = new DangDangResponse<>();
            errorResponse.setCode(-1);
            errorResponse.setMsg("系统异常: " + e.getMessage());
            return errorResponse;
        }
    }
    
}
